package com.hainatong.shiphelper.module.warehouse.fragment;

import android.os.Bundle;
import android.view.View;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hainatong.shiphelper.Constants;
import com.hainatong.shiphelper.GlobalConfig;
import com.hainatong.shiphelper.MvvmLazyFragment;
import com.hainatong.shiphelper.R;
import com.hainatong.shiphelper.databinding.FragmentRukuTaskBinding;
import com.hainatong.shiphelper.mainhome.ComFragmentActivity;
import com.hainatong.shiphelper.module.warehouse.SupplierActivity;
import com.hainatong.shiphelper.module.warehouse.entity.*;
import com.hainatong.shiphelper.module.warehouse.viewmodel.RuKuViewModel;
import com.hainatong.shiphelper.module.workermgr.WorkerMgrActivity;
import com.hainatong.shiphelper.module.workermgr.entity.WorkerBean;
import com.hainatong.shiphelper.module.workermgr.fragment.WorkerFragment;
import com.hainatong.shiphelper.utils.GsonUtil;
import com.hainatong.shiphelper.utils.TimeUtil;
import com.hainatong.shiphelper.widget.LoadingDialog;
import com.hainatong.shiphelper.widget.PickerDialog;
import com.hainatong.shiphelper.widget.datapicker.CustomDatePicker;
import com.hainatong.mvvmbase.rxbus.RxBusBaseMessage;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.List;


public class RukuTaskFragment extends MvvmLazyFragment<FragmentRukuTaskBinding , RuKuViewModel>
{
    private static String RUKU_TASK_TAG = "RukuTaskFragment";

    private ImpaShelfCodeBean impaShelfCode;
    private ImpaBean theImpa;
    private List<String> piciList;

    private LoadingDialog loading;

    private PickerDialog pickerDialog;

    private CustomDatePicker datePicker;
    // 入库请求 参数
    private RukuParamBean rukuParam;

    private RukuGoodsInfo rukuGoods;

    public static RukuTaskFragment newInstance(String scanCode)
    {
        Bundle bundle = new Bundle();
        bundle.putString( RUKU_TASK_TAG , scanCode );
        RukuTaskFragment taskFragment = new RukuTaskFragment();
        taskFragment.setArguments( bundle );
        return taskFragment;
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.fragment_ruku_task;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected void initParameters()
    {
        Bundle args = getArguments();
        if(  args != null )
        {
           String shelfUuidStr = args.getString(RUKU_TASK_TAG , "");
           if( !StringUtils.isEmpty( shelfUuidStr ) )
           {
               impaShelfCode = GsonUtil.json2Obj( shelfUuidStr , ImpaShelfCodeBean.class );
           }
        }
    }

    @Override
    protected void onRetryBtnClick()
    {
    }

    @Override
    protected void initView(View view)
    {
        loading = new LoadingDialog( getActivity(), getString( R.string.loading ) );
        rukuParam = new RukuParamBean();

        pickerDialog = new PickerDialog(getActivity(), (selectStr, position) -> {
            //批次号
            rukuParam.setBatchNo( selectStr );
            viewDataBinding.tvPiciTime.setText( selectStr );
            ToastUtils.showShort( selectStr );
        });
        initDataPicker();
        //批次
        viewDataBinding.btnPiciSelect.setOnClickListener( v -> {

            if(  piciList != null && !piciList.isEmpty()  )
            {
                //已经 获取过 批次了
                pickerDialog.showPickContent(piciList);
            }
            else
            {
                if( ObjectUtils.isNotEmpty( impaShelfCode ) )
                {
                    loading.show();
                    viewModel.queryImpaPici( impaShelfCode.getImpaCode() );
                }
            }
        } );
        // 入库 时间
        viewDataBinding.btnRukuTimeSelect.setOnClickListener( v -> {
            datePicker.show( TimeUtil.getTimeStandard( System.currentTimeMillis() ) );
        } );
        // 选择 负责人
        viewDataBinding.btnSelectWorker.setOnClickListener( v -> {
            // 通知 开始 选 用户
            LiveEventBus.get(WorkerFragment.SELECT_WORKER_TAG ,Boolean.class ).post( true );
            WorkerMgrActivity.start( getActivity() );
        } );
        // 这里 不知道 提交入库时 是否需要供应商信息  表里显示 只有 破损提交时 需要供应商
        //选择供应商
        viewDataBinding.btnSupplierSelect.setOnClickListener( v -> {

            SupplierActivity.start(getActivity());
        } );


        // 提交 入库
        viewDataBinding.btnAddToShelf.setOnClickListener( v -> {
            //入库
            String countStr = viewDataBinding.etCountSum.getText().toString();
            if( StringUtils.isEmpty( countStr ) )
            {
                ToastUtils.showShort( "输入数量" );
                return;
            }
            int count = Integer.parseInt( countStr );

            rukuParam.setCount( count );


            String indateStr = viewDataBinding.etBaozhiqiCount.getText().toString();
            if( StringUtils.isEmpty( indateStr ) )
            {
                ToastUtils.showShort( "输入保质期" );
                return;
            }
            int indate = Integer.parseInt( indateStr );
            // 设置 保质期
            rukuParam.setIndate( indate );
            //添加 时间  添加人信息

            rukuParam.setCreateID( GlobalConfig.getInstance().getUserInfo().getUser_no() );
            rukuParam.setCreator( GlobalConfig.getInstance().getUserInfo().getUserTrueName() );

            loading.show();
            // 入库 请求
            viewModel.rukuTask( rukuParam );
        } );
        // 跳转 破损提交
        viewDataBinding.btnBroken.setOnClickListener( v -> {

            // 跳转 破损提交
            Bundle bundle = new Bundle();
            bundle.putString( Constants.FRAGMNET_TYPE, Constants.VIEW_TYPE_BROKEN_SUB);
            bundle.putString( Constants.SCAN_CONTENT_CODE, impaShelfCode.getImpaCode());
            ComFragmentActivity.start( getActivity(),bundle );

        } );
        //负责人
        LiveEventBus.get(WorkerFragment.SELECT_WORKER_TAG, WorkerBean.class)
                    .observeSticky( this , workerBean -> {
                        // 拿到 选择的 负责人
                        if( ObjectUtils.isNotEmpty( workerBean ) )
                        {
                            viewDataBinding.tvFuzheWorkerName.setText( workerBean.getUserTrueName()  );
                            rukuParam.setCharge_user_id( workerBean.getUuid() );
                            rukuParam.setCharge_user( workerBean.getUserTrueName() );
                        }
                    } );
        //供应商
        LiveEventBus.get(SupplierActivity.SUPPLIER_RESULT, SupplierBean.class)
                .observeSticky(this,suppliser -> {
                    viewDataBinding.tvSupplier.setText( suppliser.getSupplier_name() );
                    rukuParam.setSupplier(suppliser.getSupplier_name());
                    rukuParam.setSupplier_id(suppliser.getUuid() );
                });
    }

    @Override
    protected void lazyLoad()
    {
        if(ObjectUtils.isNotEmpty( impaShelfCode ))
        {
            //这里 仓库ID 就是 货架的UUID
            rukuParam.setWarehouse_id( impaShelfCode.getShelfUuid() );
            rukuParam.setImpa_code( impaShelfCode.getImpaCode() );
            viewModel.queryImpaByCode( impaShelfCode.getImpaCode() );
        }
        //拿到 物资信息 后
        viewModel.getImpaResult().observe(this , result -> {
            if( result.isSuccess() )
            {
                theImpa = result.getData();
                // 列表里的 入库信息
                rukuGoods = new RukuGoodsInfo();
                // 设置 物资名称等
                rukuGoods.setImpaBean( theImpa );
                rukuParam.setImpa_id( theImpa.getUuid() );

                //默认 负责人 为 提交的 用户
                if( ObjectUtils.isNotEmpty(GlobalConfig.getInstance().getUserInfo()) )
                {
                    viewDataBinding.tvFuzheWorkerName.setText( GlobalConfig.getInstance().getUserInfo().getUserTrueName()  );
                    rukuParam.setCharge_user_id( GlobalConfig.getInstance().getUserInfo().getUuid() );
                    rukuParam.setCharge_user( GlobalConfig.getInstance().getUserInfo().getUserTrueName() );
                }

                viewDataBinding.setImpabean(result.getData());
                viewDataBinding.executePendingBindings();
            }
            else
            {
                ToastUtils.showShort(result.getMsg());
            }
        });

        // 批次信息
        viewModel.getImpaBatchResult().observe(this,result -> {
            loading.hide();
            if( result.isSuccess() )
            {
                piciList = result.getData();
                pickerDialog.showPickContent(piciList);
            }
            else
            {
                ToastUtils.showShort( result.getMsg()  );
            }
        });
        // 入库 任务
        viewModel.getRukuResult().observe( this ,result -> {
            loading.hide();
            if( result.isSuccess() )
            {
                RukuParamBean rukuOverWuzhi =  result.getData();
                rukuGoods.setRukuParamBean( rukuOverWuzhi );
                // 入一次 添加一次
                LiveEventBus.get(RukuAddFragment.RUKU_REFRESH , RxBusBaseMessage.class)
                        .post(new RxBusBaseMessage(RukuAddFragment.RUKU_ADD_CODE ,rukuGoods ) );
                // 从 入库 任务列表 来的
                if(impaShelfCode.isFromRuKuAdd())
                {
                    getActivity().finish();
                }
                else
                {
                    // 第一次 添加完成后 进入任务列表
                    // 跳转 已入库添加  列表   货架 uuid
                    ComFragmentActivity.startViewByParam( getActivity(),Constants.VIEW_TYPE_RUKU_ADD,impaShelfCode.getShelfUuid(),true );
                }
            }
            else
            {
                ToastUtils.showShort( result.getMsg() );
            }
        } );

    }

    private void initDataPicker()
    {
        datePicker = new CustomDatePicker(getActivity(), new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time)
            {

                viewDataBinding.tvRukuTime.setText( TimeUtil.getTimeYMDHS2YMD( time ) );
                rukuParam.setCreateDate( TimeUtil.getTimeYMDHS2YMD( time )  );
                // 获取时间 一个long值
                //long resultTime = TimeUtil.parseDate(time).getTime();
                LogUtils.e("CustomDatePicker", time + "  时间= " + TimeUtil.getTimeYMDHS2YMD( time ));
            }
        } , "2000-01-01 00:00" ,  TimeUtil.getTimeStandard((System.currentTimeMillis() )));
        // + 1000*60*60*24*365*5
        // 初始化日期格式请用：yyyy-MM-dd HH:mm
        // HH:mm，否则不能正常运行 //false 不显示时和分
        datePicker.showSpecificTime(false);
        datePicker.setIsLoop(true); // false 不允许循环滚动
        /*
         * //currentTime.setText(now); datePicker = new CustomDatePicker(this, new
         * CustomDatePicker.ResultHandler() {
         * @Override public void handle(String time) { // 回调接口，获得选中的时间 //currentTime.setText(time);
         * } }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
         * datePicker.showSpecificTime(true); // 显示时和分 datePicker.setIsLoop(true); // 允许循环滚动
         */
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        loading.dismiss();
    }
}
